﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public enum BlockType
{
    None    = 0,
    Drit    = 1,
    Grass   = 2,
    Gravel  = 4,
}

public class Chunk : MonoBehaviour
{
    public static List<Chunk> chunks = new List<Chunk>();

    public static int width = 30;
    public static int height = 30;

    public int seed;

    public float baseHeight = 10;
    public float freq = 0.025f;
    public float amp = 1;

    BlockType[,,] map;

    Mesh chunkMesh;

    Vector3 offset0;
    Vector3 offset1;
    Vector3 offset2;

    MeshRenderer meshRenderer;
    MeshCollider meshCollider;
    MeshFilter meshFilter;

    private void Start()
    {
        
    }

    private void InitMap()
    {
        Random.InitState(seed);

        offset0 = new Vector3(Random.value * 1000, Random.value * 1000, Random.value * 1000);
        offset1 = new Vector3(Random.value * 1000, Random.value * 1000, Random.value * 1000);
        offset2 = new Vector3(Random.value * 1000, Random.value * 1000, Random.value * 1000);

        map = new BlockType[width, height, width];

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                for(int z = 0; z < width; z++)
                {
                    map[x, y, z] = GenerateBlockType(new Vector3(x, y, z) + transform.position);
                }
            }
        }

        BuildChunk();

    }

    private void BuildChunk()
    {
        throw new NotImplementedException();
    }

    private BlockType GenerateBlockType(Vector3 wPos)
    {
        
    }

    int GenerateHeight(Vector3 wPos)
    {
        float x0 = (wPos.x + offset0.x) * freq;
        float y0 = (wPos.y + offset0.y) * freq;
        float z0 = (wPos.z + offset0.z) * freq;

        float x1 = (wPos.x + offset1.x) * freq;
        float y1 = (wPos.y + offset1.y) * freq;
        float z1 = (wPos.z + offset1.z) * freq;

        float x2 = (wPos.x + offset2.x) * freq;
        float y2 = (wPos.y + offset2.y) * freq;
        float z2 = (wPos.z + offset2.z) * freq;

        float noise0 = Noise.Generate(x0, y0, z0);
        float noise1 = Noise.Generate(x1, y1, z1);
        float noise2 = Noise.Generate(x2, y2, z2);

        return Mathf.FloorToInt(noise0 + noise1 + noise2 + baseHeight);

    }


}
